package com.zhiche.lisa.tms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.lisa.json.JSONUtil;
import com.lisa.syslog.SysLogUtil;
import com.lisa.syslog.model.SysLogDataPo;
import com.zhiche.lisa.config.TmsProperties;
import com.zhiche.lisa.core.enums.*;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.supports.RestfulResponse;
import com.zhiche.lisa.core.utils.Account.AccountUtil;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.oms.dao.model.Order;
import com.zhiche.lisa.oms.dao.model.OrderItem;
import com.zhiche.lisa.oms.service.IOrderItemService;
import com.zhiche.lisa.oms.service.IOrderService;
import com.zhiche.lisa.oms.service.impl.OrderServiceImpl;
import com.zhiche.lisa.tms.dao.mapper.ShipTaskMapper;
import com.zhiche.lisa.tms.dao.model.*;
import com.zhiche.lisa.tms.dao.model.bo.ShipTaskBo;
import com.zhiche.lisa.tms.dao.model.bo.ShipTaskCountBo;
import com.zhiche.lisa.tms.dao.model.bo.ShipToByLicenseBO;
import com.zhiche.lisa.tms.dto.*;
import com.zhiche.lisa.tms.dto.FourPeopleEnum;
import com.zhiche.lisa.tms.service.*;
import com.zhiche.lisa.tms.vo.DepartureConfirmationVO;
import com.zhiche.lisa.tms.vo.LogDataPo;
import com.zhiche.lisa.tms.vo.LogExportPo;
import com.zhiche.lisa.util.RandomUtil;
import com.zhiche.lisa.util.UaaUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.DateUtils;
import org.apache.http.message.BasicNameValuePair;
import org.assertj.core.util.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 运输任务 服务实现类
 * </p>
 *
 * @author qichao
 * @since 2018-06-18
 */
@Service
public class ShipTaskServiceImpl extends ServiceImpl<ShipTaskMapper, ShipTask> implements IShipTaskService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private IShipmentService shipmentService;
    @Autowired
    private ExportLogService exportLogService;
    @Autowired
    private IShipOrderItemService orderItemService;
    @Autowired
    private IOrderItemService iorderItemService;
    @Autowired
    private TmsProperties properties;
    @Autowired
    private IShipmentDetailService shipmentDetailService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private UaaUtil uaaUtil;
    @Autowired
    private IShipmentAttachService shipmentAttachService;
    @Autowired
    private TmsExplogLineService explogLineService;
    @Autowired private OrderServiceImpl orderServiceImpl;
    @Autowired
    private IShipOrderItemService shipOrderItemService;

    @Value("${erp.rmtILSShipStatUrl}")
    private String rmtILSShipStatUrl;
    @Value("${erp.updateShipOrderItemUrl}")
    private String updateShipOrderItemUrl;
    @Value("${lisa.lspm.isUnlcnFleetDriverUrl}")
    private String isUnlcnFleetDriverUrl;
    @Value("${lisa.bms.updateOrderItemUrl}")
    private String updateOrderItemUrl;
    @Value("${lisa.wms.unattendedAutoOutBoundUrl}")
    private String unattendedAutoOutBoundUrl;
    @Value("${lisa.wms.unattendedAutoInBoundUrl}")
    private String unattendedAutoInBoundUrl;
    @Value("${lisa.wms.getDespatchMsg}")
    private String getDespatchMsg;
    @Value("${lisa.socketTimeout}")
    private Integer socketTimeout;


    @Override
    public List<ShipTaskBo> getShipTaskByShipId(Long shipmentId) {
        return baseMapper.getShipTaskByShipId(shipmentId);
    }

    @Override
    public List<ShipTaskBo> getShipTaskByShipIdNoTenant(Long shipmentId) {
        return baseMapper.getShipTaskByShipIdNoTenant(shipmentId);
    }

    @Override
    public List<ShipTaskCountBo> getShipTaskCountByShipId(String shipmentCode) {
        return baseMapper.getShipTaskCountByShipIdNoTenant(shipmentCode);
    }

    @Override
    public List<ShipTaskCountBo> getlspWaybill(Long tenantId) {
        return baseMapper.getlspWaybill(tenantId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void departureConfirmation(DepartureConfirmationVO dcvo, String token) {
        ShipTask shipTaskData = baseMapper.getDriverTaskNotenant(dcvo.getCode());
        if (shipTaskData.getGmtStart() != null) {
            throw new BaseException(-1, "该车已确认发车!");
        }
        ShipTask shipTask = new ShipTask();
        if(null != dcvo.getGmtStart()){
            shipTask.setGmtStart(dcvo.getGmtStart());
        }else{
            shipTask.setGmtStart(new Date());
        }
        shipTask.setId(shipTaskData.getId());
        //当前操作人id
        String AccountId = AccountUtil.getAccountInfoFromSecurityContext().getAccountId();
        shipTask.setStartCreator(AccountId);
        shipTask.setCreator(AccountId);
        baseMapper.updateById(shipTask);
        Shipment shipmentData = shipmentService.getDriverShipmentnotenant(dcvo.getShipmentId());
        if (shipmentData != null) {
            if (shipmentData.getGmtSetoff() == null) {
                Shipment shipment = new Shipment();
                if(null != dcvo.getGmtStart()){
                    shipment.setGmtSetoff(dcvo.getGmtStart());
                }else{
                    shipment.setGmtSetoff(new Date());
                }
                shipment.setId(shipmentData.getId());
                shipmentService.updateById(shipment);
            }

            // 无人值守,发运推送WMS
            autoShipWMS(shipTaskData.getShipOrderCode(), shipmentData.getShipSourceKey(), token, unattendedAutoOutBoundUrl);
            //司机发运发送otm
            // 2019-3-12 去除发车确认图片推送OTM
//            shipOTM(token, shipTaskData, shipmentData);
            //2019-01-18 自有车队的空放指令推送ERP   正常指令以现场WMS发运为准推送ERP
            emptyOwnFleetToErp(shipmentData);
        }
    }

    public void emptyOwnFleetToErp(Shipment shipmentData) {
        if (properties.isSendToERP()
                && StringUtils.isNotBlank(shipmentData.getShipSourceKey())
                && shipmentData.getShipSourceKey().startsWith("K")) {
            EntityWrapper<ShipmentDetail> ew = new EntityWrapper<>();
            ew.eq("shipment_id", shipmentData.getId())
                    .orderBy("id", false);
            List<ShipmentDetail> details = shipmentDetailService.selectListNoTenant(ew);
            new Thread(() -> {
                if (CollectionUtils.isNotEmpty(details) && StringUtils.isNotBlank(shipmentData.getDriverId())) {
                    for (ShipmentDetail shipmentDetail : details) {
                        List<NameValuePair> headNamePairs = Lists.newArrayList();
                        String resToken = uaaUtil.getTenantToken("tech-" + shipmentData.getTenantId());
                        logger.info("判断司机是否是中联自有 获取token:{}", resToken);
                        headNamePairs.add(new BasicNameValuePair("Authorization", resToken));
                        String result = HttpClientUtil.get(isUnlcnFleetDriverUrl + "/" + shipmentData.getDriverId(), headNamePairs, null, properties.getSocktTimeOut());
                        logger.info("判断司机是否是中联自有车队返回结果 url:{},erpResult:{}", isUnlcnFleetDriverUrl + "/" + shipmentData.getDriverId(), result);
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        String data = jsonObject.getString("data");
                        if (StringUtils.isNotBlank(data)) {
                            ShipmentStatToErpDTO shipmentStatToErpDTO = new ShipmentStatToErpDTO();
                            shipmentStatToErpDTO.setShipmentId(shipmentData.getShipSourceKey());
                            shipmentStatToErpDTO.setDestLocationSequence(String.valueOf(shipmentDetail.getShipTaskDestOrder()));
                            shipmentStatToErpDTO.setOriginLocationSequence(String.valueOf(shipmentDetail.getShipTaskOriginOrder()));
                            shipmentStatToErpDTO.setTruckTime(Objects.isNull(shipmentData.getGmtSetoff()) ? new Date() : shipmentData.getGmtSetoff());
                            shipmentStatToErpDTO.setArriveTime(shipmentData.getGmtDeliver());
                            shipmentStatToErpDTO.setShipTime(Objects.isNull(shipmentData.getGmtSetoff()) ? new Date() : shipmentData.getGmtSetoff());
                            String paramJson = JSONObject.toJSONString(shipmentStatToErpDTO);
                            //fix  增加推送ERP日志记录
                            TmsExplogLine explogLine = new TmsExplogLine();
                            explogLine.setExportType(InterfaceEventEnum.BS_OP_DELIVERY.getCode());
                            explogLine.setExportKey(shipmentData.getShipSourceKey());
                            explogLine.setTargetSys("ERP");
                            explogLine.setInterfaceUrl(rmtILSShipStatUrl);
                            explogLine.setDataContent(paramJson);
                            explogLine.setGmtCreate(new Date());
                            explogLine.setRemarks("空放司机发运推送ERP");
                            try {
                                logger.info("departureConfirmation 空放指令发运传ERP url:{},param:{}", rmtILSShipStatUrl, paramJson);
                                String postJson = HttpClientUtil.postJson(rmtILSShipStatUrl, null, paramJson, properties.getSocktTimeOut());
                                logger.info("departureConfirmation 空放指令发运传ERP结果:{}", postJson);
                                explogLine.setExportResponse(postJson);
                                explogLine.setExportStatus(TableStatusEnum.STATUS_Y.getCode());
                            } catch (Exception e) {
                                logger.error("departureConfirmation 空放指令发运传ERP超时异常:url:{},params:{}", rmtILSShipStatUrl, paramJson);
                                explogLine.setExportStatus(TableStatusEnum.STATUS_N.getCode());
                            }
                            explogLineService.insert(explogLine);
                        }
                    }
                }
            }).start();
        }
    }

    /**
     * 无人值守,发运推送WMS
     */
    private void autoShipWMS(String orderCode, String shipSourceKey, String token, String url) {

        List<NameValuePair> headerParams = Lists.newArrayList();
        headerParams.add(new BasicNameValuePair("Authorization", token));

        HashMap<String, String> param = Maps.newHashMap();
        param.put("tmsOrderCode", orderCode);
        Order order = orderService.queryOrderFromTms(param);
        if (Objects.nonNull(order)) {

            EntityWrapper<ShipOrderItem> ew = new EntityWrapper<>();
            ew.eq("ship_order_code", orderCode)
                    .eq("is_delete", TableStatusEnum.STATUS_0.getCode())
                    .orderBy("id", false);
            List<ShipOrderItem> orderItems = orderItemService.selectList(ew);
            for (ShipOrderItem soi : orderItems) {
                // 推送WMS
                Map<String, String> map = new HashMap<>();
                map.put("releaseGid", soi.getItemSourceKey());// 系统单号
                map.put("shipmentGid", shipSourceKey); // 调度指令ID
                map.put("vin", soi.getIssueItemId()); // 车架号
                String jsonParam = JSONObject.toJSONString(map);
                try {
                    new Thread(() -> {
                        logger.info("departureConfirmation 推送WMS发运 URL:{},PARAM:{}", url, jsonParam);
                        String postJson = HttpClientUtil.postJson(url, headerParams, jsonParam, properties.getSocktTimeOut());
                        logger.info("departureConfirmation 推送WMS发运响应结果:{}", postJson);
                    }).start();
                } catch (Exception e) {
                    logger.error("departureConfirmation 推送WMS发运超时异常:url:{},params:{}", url, jsonParam);
                }
            }
        }
    }

    private void shipOTM(String token, ShipTask shipTaskDate, Shipment shipment) {
        List<ShipmentAttach> shipmentAttachs = getShipmentAttaches(shipTaskDate.getCode(), TableStatusEnum.STATUS_10.getCode());
        String shipToKeys = getShipToKeys(shipmentAttachs);
        HashMap<String, String> param = Maps.newHashMap();
        param.put("shipmentGid", shipment.getShipSourceKey());
        param.put("shipPicKeys", shipToKeys);
        param.put("departTime", DateUtils.formatDate(new Date(), "yyyy/MM/dd HH:mm:ss"));
        String jsonParam = JSONObject.toJSONString(param);
        ArrayList<NameValuePair> headers = Lists.newArrayList();
        headers.add(new BasicNameValuePair("Authorization", token));
        new Thread(() -> {
            try {
                logger.info("司机发运--> 回传OTM url:{},param:{}", properties.getIntegrationhost() + IntegrationURIEnum.TMS_SHIP_URI.getAddress(),
                        jsonParam);
                String resJson = HttpClientUtil.postJson(properties.getIntegrationhost() + IntegrationURIEnum.TMS_SHIP_URI.getAddress(),
                        headers, jsonParam, properties.getSocktTimeOut());
                logger.info("departureConfirmation 回传OTM指令号响应结果:{}", resJson);
            } catch (Exception e) {
                logger.error("departureConfirmation 回传OTM指令号超时异常:url:{},params:{}", properties.getIntegrationhost() + IntegrationURIEnum.TMS_SHIP_URI.getAddress(), jsonParam);
            }
        }).start();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void shippingTo(ShipToByLicenseBO shipToByLicenseBO, String token) {
        if (StringUtils.isEmpty(shipToByLicenseBO.getShipTaskCode())) {
            throw new BaseException(-1, "运输任务code不能为空");
        }
        // 2019-1-23 运抵添加发运校验
        checkDispatch(shipToByLicenseBO,token);

        List<ShipmentAttach> shipmentAttachs = getShipmentAttaches(shipToByLicenseBO.getShipTaskCode(), TableStatusEnum.STATUS_20.getCode());
        //更新运输任务交付时间
        ShipTask shipTaskData = baseMapper.getDriverTaskNotenant(shipToByLicenseBO.getShipTaskCode());
        if (shipTaskData.getGmtFinish() == null) {
            ShipTask shipTask = new ShipTask();
            shipTask.setId(shipTaskData.getId());
            long nextDate = getNextDay(new Date());
            if(null != shipToByLicenseBO.getGmtFinish()){
                if (shipToByLicenseBO.getGmtFinish().getTime()>nextDate){
                    throw new BaseException(-1, "运抵时间选择有误！");
                }else{
                    shipTask.setGmtFinish(shipToByLicenseBO.getGmtFinish());
                }
            }else {
                shipTask.setGmtFinish(new Date());
            }
            this.updateById(shipTask);
        } else {
            throw new BaseException(-1, "该运输任务已运抵，不能重复操作！");
        }
        // 查询装车单下面的运输任务
        int isOk = 0;
        List<ShipTaskCountBo> shipTaskCountBoLists = this.getShipTaskCountByShipId(shipToByLicenseBO.getShipmentCode());
        for (ShipTaskCountBo shipTaskCountBoList : shipTaskCountBoLists) {
            if (shipTaskCountBoList.getGmtFinish() == null) {
                isOk = 1;
                break;
            }
        }
        // 推送WMS
        EntityWrapper<Shipment> stEW = new EntityWrapper<>();
        stEW.eq("a.code", shipTaskData.getCode())
                .orderBy("a.id", false);
        List<Shipment> shipmentDatas = shipmentService.queryShipDataWms(stEW);
        if (CollectionUtils.isNotEmpty(shipmentDatas)) {
            Shipment shipmentData = shipmentDatas.get(0);
            // 推送wms
            autoShipWMS(shipTaskData.getShipOrderCode(),
                    shipmentData.getShipSourceKey(),
                    token,
                    unattendedAutoInBoundUrl);
            // 推送运抵到OTM
            // 2019-4.26 空放指令运抵不推送OTM
            if(null != shipmentData.getShipSourceKey() && !shipmentData.getShipSourceKey().startsWith("K")){
                shipToOTM(token, shipTaskData, shipmentAttachs);
            }
            if (isOk == 1) {
                return;
            }
            //自有车队核销传ERP运抵
            ownShipToERP(shipToByLicenseBO, shipTaskData);
            //更新装车单和发送erp运抵
            shipmentService.shipToByLicense(shipToByLicenseBO, token);
        }
    }

    private long getNextDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, +1);//+1今天的时间加一天
        date = calendar.getTime();
        return date.getTime();
    }

    public void checkDispatch(ShipToByLicenseBO shipToByLicenseBO, String token) {
        List<Map<String,Object>> list = new ArrayList<>();
        // 获取查询仓库运输任务条件
        list = baseMapper.getWmsOrderItemnoCondition(shipToByLicenseBO.getShipTaskCode());
        if(null == list || list.isEmpty()){
            throw new BaseException(-1, "未找到查询仓库数据条件，请联系管理员！" + shipToByLicenseBO.getShipTaskCode());
        }
        for(Map<String,Object> map : list){
            String shipSourcekey = (String)map.get("shipSourcekey");
            if(null != shipSourcekey && shipSourcekey.startsWith("K")){
                return;
            }
        }
        // 对接WMS拿取发运信息
        String paramJson = JSONObject.toJSONString(list);
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", token));
        List<Map<String,Object>> wmsResults = null;
        try {
            logger.info("checkDispatch info url:{},params:{} ", getDespatchMsg, paramJson);
            String wmsResult = HttpClientUtil.postJson(getDespatchMsg,headNamePairs, paramJson, socketTimeout);
            logger.info("checkDispatch result {} ", wmsResult);
            if(null == wmsResult || "".equals(wmsResult)){
                throw new BaseException("获取仓库发运信息错误！" + shipToByLicenseBO.getShipTaskCode());
            }
            RestfulResponse<List<Map<String, Object>>> response = JSONObject.parseObject(wmsResult, new TypeReference<RestfulResponse<List<Map<String, Object>>>>() {
            });
            if(null != response && null != response.getData()){
                wmsResults = response.getData();
            }
        } catch (Exception e) {
            logger.error("checkDispatch url:{},params:{} 连接超时:{}", getDespatchMsg, paramJson, e);
            throw new BaseException(e.getMessage());
        }

        if(CollectionUtils.isEmpty(wmsResults)){
            throw new BaseException(-1,"未查询到仓库发运信息！");
        }
        List<String> carNos = new ArrayList<>();
        String originLocationGid = null;
        for(Map<String,Object> map : wmsResults){
            if(!"BS_DISPATCH".equals(map.get("status")) && !"BS_ARRIVAL".equals(map.get("status"))){
                carNos.add ((String)map.get("vin"));
                if(null == originLocationGid){
                    originLocationGid = (String)map.get("originLocationGid");
                }
            }
        }
        // 有未发运的抛出异常
        if(null != carNos && !carNos.isEmpty()){
            throw new BaseException(-1, "发运地：" + originLocationGid + "还有未发运订单：" + StringUtils.join(carNos,","));
        }
    }

    /**
     * 自有车队运抵推送erp
     */
    private void ownShipToERP(ShipToByLicenseBO shipToByLicenseBO, ShipTask shipTaskData) {
        EntityWrapper<ShipmentDetail> shipmentDetailWrapper = new EntityWrapper<>();
        shipmentDetailWrapper.eq("ship_task_code", shipToByLicenseBO.getShipTaskCode())
                .orderBy("id", false);
        List<ShipmentDetail> details = shipmentDetailService.selectListNoTenant(shipmentDetailWrapper);
        if (CollectionUtils.isNotEmpty(details)) {
            ShipmentDetail shipmentDetail = details.get(0);
            Shipment shipment = shipmentService.getDriverShipmentnotenant(shipmentDetail.getShipmentId());
            if (properties.isSendToERP()) {
                new Thread(() -> {
                    List<NameValuePair> headNamePairs = com.google.common.collect.Lists.newArrayList();
                    String ownToken = uaaUtil.getTenantToken("tech-" + shipment.getTenantId());
                    logger.info("判断司机是否是中联自有 获取token:{}", ownToken);
                    headNamePairs.add(new BasicNameValuePair("Authorization", ownToken));
                    String result = HttpClientUtil.get(isUnlcnFleetDriverUrl + "/" + shipment.getDriverId(), headNamePairs, null, properties.getSocktTimeOut());
                    logger.info("判断司机是否是中联自有车队返回结果 url:{},erpResult:{}", isUnlcnFleetDriverUrl + "/" + shipment.getDriverId(), result);
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    String data = jsonObject.getString("data");
                    if (StringUtils.isNotBlank(data)) {
                        ShipmentStatToErpDTO shipmentStatToErpDTO = new ShipmentStatToErpDTO();
                        shipmentStatToErpDTO.setShipmentId(shipment.getShipSourceKey());
                        shipmentStatToErpDTO.setDestLocationSequence(String.valueOf(shipmentDetail.getShipTaskDestOrder()));
                        shipmentStatToErpDTO.setOriginLocationSequence(String.valueOf(shipmentDetail.getShipTaskOriginOrder()));
                        shipmentStatToErpDTO.setArriveTime(shipment.getGmtDeliver());
                        if(shipment.getShipSourceKey().startsWith("K")){ // 2019-2-14 空放指令拿取司机的发运时间
                            shipmentStatToErpDTO.setShipTime(shipment.getGmtSetoff());
                            shipmentStatToErpDTO.setTruckTime(shipment.getGmtSetoff());
                        }else {
                            shipmentStatToErpDTO.setShipTime(shipment.getWmsShipTime());
                            shipmentStatToErpDTO.setTruckTime(shipment.getWmsShipTime());
                        }
                        String paramJson = JSONObject.toJSONString(shipmentStatToErpDTO);
                        //fix  增加推送ERP日志记录
                        TmsExplogLine explogLine = new TmsExplogLine();
                        explogLine.setExportType(InterfaceEventEnum.BS_TRANS_ARRIVED.getCode());
                        explogLine.setExportKey(shipment.getShipSourceKey());
                        explogLine.setTargetSys("ERP");
                        explogLine.setInterfaceUrl(rmtILSShipStatUrl);
                        explogLine.setDataContent(paramJson);
                        explogLine.setGmtCreate(new Date());
                        explogLine.setRemarks("自有车队运抵推送ERP");
                        try {
                            logger.info("departureConfirmation 核销运抵传ERP --> url:{},params:{}", rmtILSShipStatUrl, paramJson);
                            String resJson = HttpClientUtil.postJson(rmtILSShipStatUrl, null, paramJson, properties.getSocktTimeOut());
                            logger.info("departureConfirmation 核销运抵传ERP结果:{},params:{}", resJson, paramJson);
                            explogLine.setExportStatus(TableStatusEnum.STATUS_Y.getCode());
                            explogLine.setExportResponse(resJson);
                        } catch (Exception e) {
                            logger.error("departureConfirmation 核销运抵传ERP超时异常:url:{},params:{}", rmtILSShipStatUrl, paramJson);
                            explogLine.setExportStatus(TableStatusEnum.STATUS_N.getCode());
                        }
                        explogLineService.insert(explogLine);
                    }

                }).start();
            }
        }
    }

    private List<ShipmentAttach> getShipmentAttaches(String shipTaskCode, String type) {
        // 判断运抵照片
        Wrapper<ShipmentAttach> shipmentAttachWrapper = new EntityWrapper<>();
        shipmentAttachWrapper.eq("ship_task_code", shipTaskCode)
                .eq("purpose", type);
        List<ShipmentAttach> shipmentAttachs = shipmentAttachService.selectList(shipmentAttachWrapper);
//        if (shipmentAttachs.isEmpty() || shipmentAttachs.size() < 2) {
//            throw new BaseException(-1, "请上传两张运输图片!");
//        }
        return shipmentAttachs;
    }

    private void shipToOTM(String token, ShipTask shipTaskDara, List<ShipmentAttach> shipmentAttachs) {
        if (properties.isSendToOTM()) {
            logger.info("shippingTo OTM 运抵回传OTM start---->");
            String orderCode = shipTaskDara.getShipOrderCode();
            List<NameValuePair> headerParams = Lists.newArrayList();
            headerParams.add(new BasicNameValuePair("Authorization", token));
            HashMap<String, String> param = Maps.newHashMap();
            param.put("tmsOrderCode", orderCode);
            Order order = orderService.queryOrderFromTms(param);
            if (Objects.nonNull(order)) {
                String shipToKeys = getShipToKeys(shipmentAttachs);

                EntityWrapper<ShipOrderItem> ew = new EntityWrapper<>();
                ew.eq("ship_order_code", orderCode)
                        .eq("is_delete", TableStatusEnum.STATUS_0.getCode())
                        .orderBy("id", false);
                List<ShipOrderItem> orderItems = orderItemService.selectList(ew);
                EntityWrapper<ShipTask> shipTaskEntityWrapper = new EntityWrapper<>();
                shipTaskEntityWrapper.eq("ship_order_code",orderCode);
                List<ShipTask> shipTasks = baseMapper.selectList(shipTaskEntityWrapper);
                Date gmtFinish = shipTasks.get(0).getGmtFinish();
                for (ShipOrderItem soi : orderItems) {
                    OTMEvent event = buildOtmEvent(order.getCustomerOrderId(), soi, InterfaceEventEnum.BS_TRANS_ARRIVED);
                    event.setShipToKeys(shipToKeys);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                    event.setOccurDate(sdf.format(gmtFinish));
                    event.setRecdDate(sdf.format(gmtFinish));
                    //传送OTM
                    String jsonParam = JSONObject.toJSONString(event);
                    String postJson="";
                    ExportLog exportLog = new ExportLog();
                    exportLog.setExportType("ARRIVAL");
                    exportLog.setExportSys(SystemEnum.OMS.getCode());
                    exportLog.setTargetSys(SystemEnum.INTEGRATION.getCode());
                    exportLog.setExportKey(soi.getId()+"");
                    exportLog.setInterfaceUrl(properties.getIntegrationhost() + IntegrationURIEnum.EVENT_URI.getAddress());
                    exportLog.setDataContent(jsonParam);
                    try {
                        logger.info("shippingTo 司机运抵 回传otm url:{},param:{}", properties.getIntegrationhost() + IntegrationURIEnum.EVENT_URI.getAddress(), jsonParam);
                        postJson = HttpClientUtil.postJson(properties.getIntegrationhost() + IntegrationURIEnum.EVENT_URI.getAddress(),
                                    null, jsonParam, properties.getSocktTimeOut());
                        exportLog.setExportResponse(postJson);
                        if (!"".equals(postJson)){
                            RestfulResponse response = JSONObject.parseObject(postJson, RestfulResponse.class);
                            exportLog.setExportStatus(response.getCode()+"");
                        }
                        logger.info("shippingTo 司机运抵 响应结果:{}", postJson);
                        } catch (Exception e) {
                            logger.error("shippingTo 司机运抵 超时异常:url:{},params:{}", properties.getIntegrationhost() + IntegrationURIEnum.EVENT_URI.getAddress(), jsonParam);
                        }
                    exportLogService.insert(exportLog);

                    /*系统日志处理  20191029 add start*/
                    String key = SystemEnum.OMS.getCode()+SystemEnum.UNDERLINE.getCode()+SystemEnum.INTEGRATION.getCode();
                    String fKey = "/shipTask/shipToOTM/"+soi.getId();
                    LogExportPo logDataPo = new LogExportPo(SystemEnum.OMS.getCode(), SystemEnum.INTEGRATION.getCode(),"BS_TRANS_ARRIVED" ,IntegrationURIEnum.EVENT_URI.getAddress(), null,soi.getItemSourceKey(),soi.getIssueItemId(),soi.getItemSourceKey(), soi.getId()+"",
                            jsonParam, 1, null, 1, 0, 1);
                    SysLogDataPo sysLogDataPo = new SysLogDataPo("EVENT_EXPORT", JSONUtil.toJsonStr(logDataPo));
                    SysLogUtil.addSysLogs(key, fKey, sysLogDataPo, Boolean.TRUE);
                    /*系统日志处理  20191029 add end*/
                }
            }
        }
    }

    private String getShipToKeys(List<ShipmentAttach> shipmentAttachs) {
        // 拿取运抵照片key
        if(null == shipmentAttachs || shipmentAttachs.isEmpty()){return null;}
        StringBuffer shipToKeysBuffer = new StringBuffer();
        for (ShipmentAttach shipmentAttach : shipmentAttachs) {
            shipToKeysBuffer.append(shipmentAttach.getAttachKey() + ",");
        }
        return String.valueOf(shipToKeysBuffer.substring(0, shipToKeysBuffer.length() - 1));
    }

    @Override
    public List<ShipTask> selectListNoTenant(EntityWrapper<ShipTask> taskEW) {
        return baseMapper.selectListNoTenant(taskEW);
    }

    /**
     * 导出发运数据到BMS
     * @return
     */
    @Override
    public String exportShip(ShipParamDTO dto) {
        String jsonString = JSONObject.toJSONString(dto);
        logger.info("ShipmentController.shipDataForBMSparams:{}", jsonString);
        String shipmentId = dto.getShipmentId();
        if (StringUtils.isNotBlank(shipmentId)) {
            //2019-1-31 修复多条指令查询提示错误,接受不了WMS发运触发不了发车款
            EntityWrapper<Shipment> shipEW = new EntityWrapper<>();
            shipEW.eq("ship_source_key", shipmentId)
                    .eq("is_delete", TableStatusEnum.STATUS_0.getCode())
                    .orderBy("id", false);
            List<Shipment> shipments = shipmentService.selectListNotenant(shipEW);
            logger.info("ShipmentController.shipDataForBMSparams 指令号:{},查询数据:{}",shipmentId, shipments);
            if (CollectionUtils.isNotEmpty(shipments)) {
                Shipment shipment = shipments.get(0);
                dto.setFleetId(shipment.getFleetId());
                dto.setFleetName(shipment.getFleetName());
                dto.setDriverGid(shipment.getDriverId());
                dto.setDriverName(shipment.getDriverName());
                dto.setProviderGid(shipment.getLspId());
                dto.setProviderName(shipment.getLspName());
                dto.setShipCode(shipment.getCode());
                dto.setTransTypeId(String.valueOf(shipment.getTransTypeId()));
                String dtoBMS = JSONObject.toJSONString(dto);
                shipOrderItemService.updateByshipmentId(dto.getOrderReleaseId(),dto.getShipTime());
                Shipment shipWms = new Shipment();
                shipWms.setId(shipment.getId());
                shipWms.setWmsShipTime(new Date(Long.valueOf(dto.getShipTime())));
                shipmentService.updateById(shipWms);
                //fix  增加推送ERP日志记录
                TmsExplogLine explogLine = new TmsExplogLine();
                explogLine.setExportType(InterfaceEventEnum.BS_OP_DELIVERY.getCode());
                explogLine.setExportKey(shipment.getShipSourceKey());
                explogLine.setTargetSys("BMS");
                explogLine.setInterfaceUrl(properties.getExportShipToBMS());
                explogLine.setDataContent(dtoBMS);
                explogLine.setGmtCreate(new Date());
                explogLine.setRemarks("发运数据推送BMS");
                try {
                    logger.info("发运数据推送BMS-->url:{},params:{}", properties.getExportShipToBMS(), dtoBMS);
                    String json = HttpClientUtil.postJson(properties.getExportShipToBMS(), null, dtoBMS, properties.getSocktTimeOut());
                    logger.info("发运数据推送BMS-->result:{}", json);
                    explogLine.setExportStatus(TableStatusEnum.STATUS_Y.getCode());
                    explogLine.setExportResponse(json);
                } catch (Exception e) {
                    logger.error("发运数据推送BMS-->超时失败 error:{}", e);
                    explogLine.setExportStatus(TableStatusEnum.STATUS_N.getCode());
                }
                explogLineService.insert(explogLine);
                //获取shipmentDetail -- 自有车队发运推送ERP
                wmsShipERP(shipment, dto);
                return "tms"+RandomUtil.game(6);
            }
        }
        return null;
    }

    /**
     * WMS发运-自有车队推送erp
     */
    private void wmsShipERP(Shipment shipment, ShipParamDTO dto) {
        EntityWrapper<ShipmentDetail> ew = new EntityWrapper<>();
        ew.eq("shipment_id", shipment.getId())
                .orderBy("id", false);
        List<ShipmentDetail> details = shipmentDetailService.selectListNoTenant(ew);
        if (CollectionUtils.isNotEmpty(details)) {
            if (properties.isSendToERP()) {
                new Thread(() -> {
                    if (StringUtils.isNotBlank(shipment.getDriverId())) {
                        ShipmentDetail shipmentDetail = details.get(0);
                        List<NameValuePair> headNamePairs = Lists.newArrayList();
                        String resToken = uaaUtil.getTenantToken("tech-" + shipment.getTenantId());
                        logger.info("判断司机是否是中联自有 获取token:{}", resToken);
                        headNamePairs.add(new BasicNameValuePair("Authorization", resToken));
                        String result = HttpClientUtil.get(isUnlcnFleetDriverUrl + "/" + shipment.getDriverId(), headNamePairs, null, properties.getSocktTimeOut());
                        logger.info("判断司机是否是中联自有车队返回结果 url:{},erpResult:{}", isUnlcnFleetDriverUrl + "/" + shipment.getDriverId(), result);
                        JSONObject jsonObject = JSONObject.parseObject(result);
                        String data = jsonObject.getString("data");
                        if (StringUtils.isNotBlank(data)) {
                            ShipmentStatToErpDTO shipmentStatToErpDTO = new ShipmentStatToErpDTO();
                            shipmentStatToErpDTO.setShipmentId(shipment.getShipSourceKey());
                            shipmentStatToErpDTO.setDestLocationSequence(String.valueOf(shipmentDetail.getShipTaskDestOrder()));
                            shipmentStatToErpDTO.setOriginLocationSequence(String.valueOf(shipmentDetail.getShipTaskOriginOrder()));
                            shipmentStatToErpDTO.setTruckTime(new Date(Long.valueOf(dto.getShipTime())));
                            shipmentStatToErpDTO.setArriveTime(shipment.getGmtDeliver());
                            shipmentStatToErpDTO.setShipTime(new Date(Long.valueOf(dto.getShipTime())));
                            String paramJson = JSONObject.toJSONString(shipmentStatToErpDTO);
                            //fix  增加推送ERP日志记录
                            TmsExplogLine explogLine = new TmsExplogLine();
                            explogLine.setExportType(InterfaceEventEnum.BS_OP_DELIVERY.getCode());
                            explogLine.setExportKey(shipment.getShipSourceKey());
                            explogLine.setTargetSys("ERP");
                            explogLine.setInterfaceUrl(rmtILSShipStatUrl);
                            explogLine.setDataContent(paramJson);
                            explogLine.setGmtCreate(new Date());
                            explogLine.setRemarks("自有车队发运推送ERP");
                            try {
                                logger.info("departureConfirmation url:{},param:{}", rmtILSShipStatUrl, paramJson);
                                String postJson = HttpClientUtil.postJson(rmtILSShipStatUrl, null, paramJson, properties.getSocktTimeOut());
                                logger.info("departureConfirmation 发运传ERP结果:{}", postJson);
                                explogLine.setExportStatus(TableStatusEnum.STATUS_Y.getCode());
                                explogLine.setExportResponse(postJson);
                            } catch (Exception e) {
                                logger.error("departureConfirmation 发运传ERP超时异常:url:{},params:{}", rmtILSShipStatUrl, paramJson);
                                explogLine.setExportStatus(TableStatusEnum.STATUS_N.getCode());
                            }
                            explogLineService.insert(explogLine);
                        }
                    }
                }).start();
            }
        }
    }

    private OTMEvent buildOtmEvent(String shipmentId, ShipOrderItem soi, InterfaceEventEnum eventEnum) {
        OTMEvent event = new OTMEvent();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        event.setExportKey(String.valueOf(soi.getId()));
        event.setCallBackUrl(null);
        event.setEventType(eventEnum.getCode());
       // event.setOccurDate(sdf.format(new Date()));
        //event.setRecdDate(sdf.format(new Date()));
        event.setSort(1);
        event.setDescribe(eventEnum.getDesc());
        event.setOrderReleaseId(soi.getItemSourceKey());
        event.setShipmentId(shipmentId);
        event.setQrCode(null);
        return event;
    }

    @Override
    public ShipTask getShipTaskByCode(String code) {
        if (StringUtils.isEmpty(code)) {
            throw new BaseException(-1, "运输任务编号不能为空");
        }
        EntityWrapper<ShipTask> ew = new EntityWrapper<>();
        ew.eq("code", code);
        return this.selectOne(ew);
    }

    @Override
    public void emptyToErps(String instructNo) {
        if(StringUtils.isEmpty(instructNo)){
            return;
        }
        String[] split = instructNo.split(",");
        List<String> instructNos= Arrays.asList(split);
        EntityWrapper<Shipment> ew = new EntityWrapper<>();
        ew.in("ship_source_key",instructNos);
        ew.eq("is_delete",0);
        List<Shipment> shipments = shipmentService.selectListNotenant(ew);
        for(Shipment shipment :shipments){
//            ShipmentInfoVO infoDTO = new ShipmentInfoVO();
//            BeanUtils.copyProperties(shipment, infoDTO);
//            infoDTO.setDriverMoble(shipment.getDriverPhone());
//            infoDTO.setDriverId(String.valueOf(shipment.getDriverId()));
//            infoDTO.setTenantId(shipment.getTenantId());
//            infoDTO.setCreator("unlcn");
//            infoDTO.setShipmentId(shipment.getShipSourceKey());
//            infoDTO.setTransactionCode("IU");
//            infoDTO.setOrderCode(order.getCode());
//            LocationVo endLocation = endLocation(shipmentInfoVO, shipment.getTenantId(), null);
//            if (endLocation == null) {
//                logger.error("获取交货点信息失败");
//            }
//            infoDTO.setEndLocation(endLocation);
//            LocationVo startLocation = startLocation(shipmentInfoVO, shipment.getTenantId(), null);
//            if (startLocation == null) {
//                logger.error("获取发货点信息失败");
//            }
//            infoDTO.setStartLocation(startLocation);
//            // 空放自有车传erp
//            orderServiceImpl.orderToErp(infoDTO, null);
            // 空放自有车发运传erp
            emptyOwnFleetToErp(shipment);
            //自有车队运抵推送erp
            ShipToByLicenseBO shipToByLicenseBO = new ShipToByLicenseBO();
            EntityWrapper<ShipmentDetail> shipmentDetailWrapper = new EntityWrapper<>();
            shipmentDetailWrapper.eq("shipment_id", shipment.getId())
                    .orderBy("id", false);
            List<ShipmentDetail> details = shipmentDetailService.selectListNoTenant(shipmentDetailWrapper);
            if(null != details && !details.isEmpty()){
                for(ShipmentDetail detail:details){
                    shipToByLicenseBO.setShipTaskCode(detail.getShipTaskCode());
                    ownShipToERP(shipToByLicenseBO, null);
                }
            }
        }

    }

    @Override
    public List<ShipOrderItem> getShipOrderItemByTaskId(String taskId) {
        return baseMapper.getShipOrderItemByTaskId(taskId);

    }

    @Override
    public void shippingToToOtm(String shipmentIds,String token) {
        String[] split = shipmentIds.split(",");
        List<String> errorShipment =new ArrayList<>();
        for (String shipmentId : split) {
            EntityWrapper<Shipment> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("ship_source_key", shipmentId.trim().replace("\n", "")).eq("is_delete",0);
            Shipment shipment = shipmentService.selectOneNoTenant(entityWrapper);
            if (Objects.isNull(shipment)){
                errorShipment.add(shipmentId);
                continue;
            }
            EntityWrapper<ShipmentDetail> detailEntityWrapper = new EntityWrapper<>();
            detailEntityWrapper.eq("shipment_id", shipment.getId());
            List<ShipmentDetail> shipmentDetails = shipmentDetailService.selectListNoTenant(detailEntityWrapper);
            for (ShipmentDetail shipmentDetail : shipmentDetails) {
                EntityWrapper<ShipTask> taskEntityWrapper = new EntityWrapper<>();
                taskEntityWrapper.eq("code", shipmentDetail.getShipTaskCode()).isNotNull("gmt_finish").eq("is_delete",0);
                List<ShipTask> shipTasks = baseMapper.selectListNoTenant(taskEntityWrapper);
                for (ShipTask shipTask : shipTasks) {
                    List<ShipmentAttach> shipmentAttachs = getShipmentAttaches(shipmentDetail.getShipTaskCode(), TableStatusEnum.STATUS_20.getCode());
                    List<NameValuePair> headerParams = Lists.newArrayList();
                    headerParams.add(new BasicNameValuePair("Authorization", token));
                    HashMap<String, String> param = Maps.newHashMap();
                    param.put("tmsOrderCode", shipTask.getShipOrderCode());
                    Order order = orderService.queryOrderFromTms(param);
                    if (Objects.nonNull(order)) {
                        String shipToKeys = getShipToKeys(shipmentAttachs);
                        EntityWrapper<ShipOrderItem> ew = new EntityWrapper<>();
                        ew.eq("ship_order_code", shipTask.getShipOrderCode())
                                .eq("is_delete", TableStatusEnum.STATUS_0.getCode())
                                .orderBy("id", false);
                        List<ShipOrderItem> orderItems = orderItemService.selectList(ew);
                        for (ShipOrderItem soi : orderItems) {
                            OTMEvent event = buildOtmEvent(order.getCustomerOrderId(), soi, InterfaceEventEnum.BS_TRANS_ARRIVED);
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                            event.setOccurDate(sdf.format(shipTask.getGmtFinish()));
                            event.setRecdDate(sdf.format(shipTask.getGmtFinish()));
                            event.setShipToKeys(shipToKeys);
                            //传送OTM
                            new Thread(() -> {
                                String jsonParam = JSONObject.toJSONString(event);
                                try {
                                    logger.info("shippingTo 司机运抵重新回传otm url:{},param:{}", properties.getIntegrationhost() + IntegrationURIEnum.EVENT_URI.getAddress(), jsonParam);
                                    String postJson = HttpClientUtil.postJson(properties.getIntegrationhost() + IntegrationURIEnum.EVENT_URI.getAddress(),
                                            null, jsonParam, properties.getSocktTimeOut());
                                    logger.info("shippingTo 司机运抵重新回传 响应结果:{}", postJson);
                                } catch (Exception e) {
                                    logger.error("shippingTo 司机运抵重新回传 超时异常:url:{},params:{}", properties.getIntegrationhost() + IntegrationURIEnum.EVENT_URI.getAddress(), jsonParam);
                                }
                            }).start();
                        }
                    }
                }
            }
        }
        if (!CollectionUtils.isEmpty(errorShipment)){
            throw new BaseException(errorShipment+"指令号不存在");
        }
    }

    @Override
    public void shippingToToERP(String shipmentIds) {
        String[] split = shipmentIds.split(",");
        for (String shipmentId : split) {
            EntityWrapper<Shipment> shipmentEntityWrapper=new EntityWrapper<>();
            shipmentEntityWrapper.eq("ship_source_key",shipmentId).eq("is_delete",0);
            Shipment shipment = shipmentService.selectOne(shipmentEntityWrapper);
            EntityWrapper<ShipmentDetail> shipmentDetailWrapper = new EntityWrapper<>();
            shipmentDetailWrapper.eq("shipment_id", shipment.getId())
                    .orderBy("id", false);
            List<ShipmentDetail> details = shipmentDetailService.selectListNoTenant(shipmentDetailWrapper);
            if (CollectionUtils.isNotEmpty(details)) {
                ShipmentDetail detail = details.get(0);
                if (shipment.getGmtDeliver()!=null) {
                    if (properties.isSendToERP()) {
                        new Thread(() -> {
                            List<NameValuePair> headNamePairs = com.google.common.collect.Lists.newArrayList();
                            String ownToken = uaaUtil.getTenantToken("tech-" + shipment.getTenantId());
                            logger.info("判断司机是否是中联自有 获取token:{}", ownToken);
                            headNamePairs.add(new BasicNameValuePair("Authorization", ownToken));
                            String result = HttpClientUtil.get(isUnlcnFleetDriverUrl + "/" + shipment.getDriverId(), headNamePairs, null, properties.getSocktTimeOut());
                            logger.info("判断司机是否是中联自有车队返回结果 url:{},erpResult:{}", isUnlcnFleetDriverUrl + "/" + shipment.getDriverId(), result);
                            JSONObject jsonObject = JSONObject.parseObject(result);
                            String data = jsonObject.getString("data");
                            if (StringUtils.isNotBlank(data)) {
                                ShipmentStatToErpDTO shipmentStatToErpDTO = new ShipmentStatToErpDTO();
                                shipmentStatToErpDTO.setShipmentId(shipment.getShipSourceKey());
                                shipmentStatToErpDTO.setDestLocationSequence(String.valueOf(detail.getShipTaskDestOrder()));
                                shipmentStatToErpDTO.setOriginLocationSequence(String.valueOf(detail.getShipTaskOriginOrder()));
                                shipmentStatToErpDTO.setArriveTime(shipment.getGmtDeliver());
                                if (shipment.getShipSourceKey().startsWith("K")) { // 2019-2-14 空放指令拿取司机的发运时间
                                    shipmentStatToErpDTO.setShipTime(shipment.getGmtSetoff());
                                    shipmentStatToErpDTO.setTruckTime(shipment.getGmtSetoff());
                                } else {
                                    List<ShipOrderItem> shipOrderItems=shipOrderItemService.selectByShipmentId(shipmentId);
                                    if (CollectionUtils.isNotEmpty(details)){
                                        ShipOrderItem shipOrderItem = shipOrderItems.get(0);
                                        shipmentStatToErpDTO.setShipTime(shipOrderItem.getWmsShipTime());
                                        shipmentStatToErpDTO.setTruckTime(shipOrderItem.getWmsShipTime());
                                    }
                                }
                                String paramJson = JSONObject.toJSONString(shipmentStatToErpDTO);
                                //fix  增加推送ERP日志记录
                                TmsExplogLine explogLine = new TmsExplogLine();
                                explogLine.setExportType(InterfaceEventEnum.BS_TRANS_ARRIVED.getCode());
                                explogLine.setExportKey(shipment.getShipSourceKey());
                                explogLine.setTargetSys("ERP");
                                explogLine.setInterfaceUrl(rmtILSShipStatUrl);
                                explogLine.setDataContent(paramJson);
                                explogLine.setGmtCreate(new Date());
                                explogLine.setRemarks("自有车队运抵推送ERP");
                                try {
                                    logger.info("departureConfirmation 核销运抵传ERP --> url:{},params:{}", rmtILSShipStatUrl, paramJson);
                                    String resJson = HttpClientUtil.postJson(rmtILSShipStatUrl, null, paramJson, properties.getSocktTimeOut());
                                    logger.info("departureConfirmation 核销运抵传ERP结果:{},params:{}", resJson, paramJson);
                                    explogLine.setExportStatus(TableStatusEnum.STATUS_Y.getCode());
                                    explogLine.setExportResponse(resJson);
                                } catch (Exception e) {
                                    logger.error("departureConfirmation 核销运抵传ERP超时异常:url:{},params:{}", rmtILSShipStatUrl, paramJson);
                                    explogLine.setExportStatus(TableStatusEnum.STATUS_N.getCode());
                                }
                                explogLineService.insert(explogLine);
                            }
                        }).start();
                    }
                }
            }
        }

    }

    @Override
    public void updateShipOrder(ReleaseDTO releaseDTO) {

        if (StringUtils.isEmpty(releaseDTO.getShipmentGid())) {
            throw new BaseException("指令号不能为空！");
        }
        if (StringUtils.isEmpty(releaseDTO.getReleaseGid())) {
            throw new BaseException("系统运单号不能为空！");
        }
        ShipOrderItem shipOrderItem = new ShipOrderItem();
        OrderItem orderItem = new OrderItem();
        if (!StringUtils.isEmpty(releaseDTO.getCiamsId())) {
            shipOrderItem.setCiamsId(releaseDTO.getCiamsId());
        }
        if (!StringUtils.isEmpty(releaseDTO.getCusWaybillNo())) {
            shipOrderItem.setCusWaybillId(releaseDTO.getCusWaybillNo());
        }
        if (!StringUtils.isEmpty(releaseDTO.getVin())) {
            shipOrderItem.setIssueItemId(releaseDTO.getVin());
            orderItem.setIssueItemId(releaseDTO.getVin());
        }
        EntityWrapper<ShipOrderItem> shipOrderItemEntityWrapper = new EntityWrapper<>();
        shipOrderItemEntityWrapper.eq("item_source_key", releaseDTO.getReleaseGid());
        ShipOrderItem shipOrderItem1 = shipOrderItemService.selectOne(shipOrderItemEntityWrapper);
        if (Objects.isNull(shipOrderItem1)){
            throw new BaseException("系统订单号不存在！");
        }
        //根据指令号查询司机信息
        EntityWrapper<Shipment> ew = new EntityWrapper<>();
        ew.eq("ship_source_key", releaseDTO.getShipmentGid());
        Shipment shipment = shipmentService.selectOne(ew);
        if (Objects.isNull(shipment)){
            throw new BaseException("指令号不存在！");
        }

        shipOrderItemService.update(shipOrderItem, shipOrderItemEntityWrapper);

        EntityWrapper<OrderItem> orderItemEntityWrapper = new EntityWrapper<>();
        orderItemEntityWrapper.eq("item_source_key", releaseDTO.getReleaseGid());
        iorderItemService.update(orderItem, orderItemEntityWrapper);


        if (StringUtils.isNotBlank(shipment.getDriverId())) {
            List<NameValuePair> headNamePairs = Lists.newArrayList();
            String resToken = uaaUtil.getTenantToken("tech-" + shipment.getTenantId());
            logger.info("判断司机是否是中联自有 获取token:{}", resToken);
            headNamePairs.add(new BasicNameValuePair("Authorization", resToken));
            String result = HttpClientUtil.get(isUnlcnFleetDriverUrl + "/" + shipment.getDriverId(), headNamePairs, null, properties.getSocktTimeOut());
            logger.info("判断司机是否是中联自有车队返回结果 url:{},erpResult:{}", isUnlcnFleetDriverUrl + "/" + shipment.getDriverId(), result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String data = jsonObject.getString("data");
            if (StringUtils.isNotBlank(data)) {
                String paramJson = JSONObject.toJSONString(releaseDTO);
                TmsExplogLine explogLine = new TmsExplogLine();
                explogLine.setExportType("BS_UPDATE");
                explogLine.setExportKey(shipment.getShipSourceKey());
                explogLine.setTargetSys("ERP");
                explogLine.setInterfaceUrl(updateShipOrderItemUrl);
                explogLine.setDataContent(paramJson);
                explogLine.setGmtCreate(new Date());
                explogLine.setRemarks("自有车队订单信息修改推送ERP");
                try {
                    logger.info("自有车队订单信息修改推送ERP url:{},param:{}", updateShipOrderItemUrl, paramJson);
                    String postJson = HttpClientUtil.postJson(updateShipOrderItemUrl, null, paramJson, properties.getSocktTimeOut());
                    logger.info("自有车队订单信息修改推送ERP 结果:{}", postJson);
                    explogLine.setExportStatus(TableStatusEnum.STATUS_Y.getCode());
                    explogLine.setExportResponse(postJson);
                } catch (Exception e) {
                    logger.error("自有车队订单信息修改推送ERP 超时异常:url:{},params:{}", updateShipOrderItemUrl, paramJson);
                    explogLine.setExportStatus(TableStatusEnum.STATUS_N.getCode());
                }
                explogLineService.insert(explogLine);
            }
        }
        //推送bms
        if (FourPeopleEnum.JST.getId().equals(shipment.getLspId())
                || FourPeopleEnum.JX.getId().equals(shipment.getLspId())
                || FourPeopleEnum.LYTD.getId().equals(shipment.getLspId())
                || FourPeopleEnum.YJ.getId().equals(shipment.getLspId())) {
            new Thread(() -> {
                String paramJson = JSONObject.toJSONString(releaseDTO);
                TmsExplogLine explogLine = new TmsExplogLine();
                explogLine.setExportType("BS_UPDATE");
                explogLine.setExportKey(shipment.getShipSourceKey());
                explogLine.setTargetSys("BMS");
                explogLine.setInterfaceUrl(updateOrderItemUrl);
                explogLine.setDataContent(paramJson);
                explogLine.setGmtCreate(new Date());
                explogLine.setRemarks("订单信息修改推送BMS");
                try {
                    String res = HttpClientUtil.postJson(updateOrderItemUrl, null, paramJson, properties.getSocktTimeOut());
                    logger.info("运单信息修改推送BMS--start url:{},result:{}", updateOrderItemUrl, res);
                    explogLine.setExportStatus(TableStatusEnum.STATUS_Y.getCode());
                    explogLine.setExportResponse(res);
                } catch (Exception e) {
                    logger.error("运单信息修改推送BMS 超时异常:url:{},params:{}", updateOrderItemUrl, paramJson);
                    explogLine.setExportStatus(TableStatusEnum.STATUS_N.getCode());
                }
                explogLineService.insert(explogLine);
            }).start();
        }
    }

    @Override
    public Map<String,Object> getDevilerDate(String orderRealeseGid) {
        Map<String,Object> map = new HashMap<>();
        Date devilerDate = baseMapper.getDevilerDate(orderRealeseGid);
        if (devilerDate==null){
            map.put("deliverDate",null);
            return map;
        }
        //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //String format = simpleDateFormat.format(devilerDate);
        map.put("deliverDate",devilerDate);
        return map;
    }

}